<!--
 * @Description: 任务表单组件
-->
<template>
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑任务' : '发布新任务'"
      width="800px"
      :close-on-click-modal="false"
      @close="handleClose"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-width="100px"
        class="task-form"
      >
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="任务标题" prop="title">
              <el-input
                v-model="formData.title"
                placeholder="请输入任务标题"
                maxlength="100"
                show-word-limit
              />
            </el-form-item>
          </el-col>
          
          <el-col :span="12">
            <el-form-item label="所属部门" prop="department">
              <el-select
                v-model="formData.department"
                placeholder="请选择所属部门"
                style="width: 100%"
              >
                <el-option 
                  v-for="dept in departmentOptions" 
                  :key="dept"
                  :label="dept" 
                  :value="dept" 
                />
              </el-select>
            </el-form-item>
          </el-col>
          
          <el-col :span="12">
            <el-form-item label="任务类型" prop="taskType">
              <el-input
                v-model="formData.taskType"
                placeholder="请输入任务类型"
              />
            </el-form-item>
          </el-col>
          
          <el-col :span="12">
            <el-form-item label="优先级" prop="priority">
              <el-select
                v-model="formData.priority"
                placeholder="请选择优先级"
                style="width: 100%"
              >
                <el-option label="紧急" value="urgent">
                  <div class="priority-option urgent">
                    <el-icon><Warning /></el-icon>
                    紧急
                  </div>
                </el-option>
                <el-option label="高" value="high">
                  <div class="priority-option high">
                    <el-icon><ArrowUp /></el-icon>
                    高
                  </div>
                </el-option>
                <el-option label="中" value="medium">
                  <div class="priority-option medium">
                    <el-icon><Minus /></el-icon>
                    中
                  </div>
                </el-option>
                <el-option label="低" value="low">
                  <div class="priority-option low">
                    <el-icon><ArrowDown /></el-icon>
                    低
                  </div>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          
          <el-col :span="12">
            <el-form-item label="任务状态" prop="status">
              <el-select
                v-model="formData.status"
                placeholder="请选择任务状态"
                style="width: 100%"
              >
                <el-option label="待处理" value="pending" />
                <el-option label="进行中" value="in-progress" />
                <el-option label="已完成" value="completed" />
                <el-option label="已取消" value="cancelled" />
              </el-select>
            </el-form-item>
          </el-col>
          
          <el-col :span="12">
            <el-form-item label="截止时间" prop="deadline">
              <el-date-picker
                v-model="formData.deadline"
                type="date"
                placeholder="请选择截止时间"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                style="width: 100%"
                :disabled-date="disabledDate"
              />
            </el-form-item>
          </el-col>
          
          <el-col :span="12">
            <el-form-item label="分配人员" prop="assignedTo">
              <el-select
                v-model="formData.assignedTo"
                multiple
                placeholder="请选择分配人员"
                style="width: 100%"
                @change="handleAssignedToChange"
              >
                <el-option 
                  v-for="person in personnelList" 
                  :key="person.name"
                  :label="`${person.name} (${person.department})`" 
                  :value="person.name"
                >
                  <div class="personnel-option">
                    <span class="name">{{ person.name }}</span>
                    <span class="department">{{ person.department }}</span>
                    <span class="nature">{{ person.personnelNature }}</span>
                  </div>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          
          <el-col :span="24">
            <el-form-item label="任务描述" prop="description">
              <el-input
                v-model="formData.description"
                type="textarea"
                :rows="4"
                placeholder="请输入任务描述"
                maxlength="500"
                show-word-limit
              />
            </el-form-item>
          </el-col>
          
          <el-col :span="24">
            <el-form-item label="备注">
              <el-input
                v-model="formData.remarks"
                type="textarea"
                :rows="3"
                placeholder="请输入备注信息（可选）"
                maxlength="300"
                show-word-limit
              />
            </el-form-item>
          </el-col>
          
          <el-col :span="24">
            <el-form-item label="附件">
              <el-upload
                v-model:file-list="fileList"
                class="upload-demo"
                :action="uploadUrl"
                :on-preview="handlePreview"
                :on-remove="handleRemove"
                :before-upload="beforeUpload"
                multiple
                :limit="5"
              >
                <el-button type="primary">
                  <el-icon><UploadFilled /></el-icon>
                  上传附件
                </el-button>
                <template #tip>
                  <div class="el-upload__tip">
                    支持jpg/png/pdf/doc/docx/xls/xlsx格式，单个文件大小不超过10MB，最多5个文件
                  </div>
                </template>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleClose">取消</el-button>
          <el-button @click="handleSave(false)">保存草稿</el-button>
          <el-button type="primary" @click="handleSave(true)" :loading="saving">
            {{ isEdit ? '更新任务' : '发布任务' }}
          </el-button>
        </div>
      </template>
    </el-dialog>
  </template>
  
  <script setup lang="ts">
  import { ref, computed, watch, nextTick } from 'vue';
  import { ElMessage } from 'element-plus';
  import { 
    Warning, 
    ArrowUp, 
    ArrowDown, 
    Minus, 
    UploadFilled 
  } from '@element-plus/icons-vue';
  import type { FormInstance, FormRules, UploadFile } from 'element-plus';
  
  // 接口定义
  interface PersonnelInfo {
    index: number;
    personnelCategory: string;
    department: string;
    name: string;
    gender: string;
    education: string;
    degree: string;
    graduatedFrom: string;
    personnelNature: string;
    workContent: string;
    workLocation: string;
    entryDate: string;
    contractStartDate: string;
    contractEndDate: string;
  }
  
  interface TaskInfo {
    id?: string;
    title: string;
    description: string;
    assignedTo: string[];
    assignedToNames: string[];
    status: 'pending' | 'in-progress' | 'completed' | 'cancelled';
    priority: 'low' | 'medium' | 'high' | 'urgent';
    createdAt?: string;
    deadline: string;
    department: string;
    taskType: string;
    attachments?: string[];
    remarks?: string;
  }
  
  // Props 和 Emits
  const props = defineProps<{
    modelValue: boolean;
    task?: TaskInfo | null;
    personnelList: PersonnelInfo[];
  }>();
  
  const emit = defineEmits<{
    'update:modelValue': [value: boolean];
    save: [task: TaskInfo];
    cancel: [];
  }>();
  
  // 数据
  const formRef = ref<FormInstance>();
  const saving = ref(false);
  const fileList = ref<UploadFile[]>([]);
  const uploadUrl = ref('https://jsonplaceholder.typicode.com/posts/'); // 示例上传地址
  
  // 表单数据
  const formData = ref<TaskInfo>({
    title: '',
    description: '',
    assignedTo: [],
    assignedToNames: [],
    status: 'pending',
    priority: 'medium',
    deadline: '',
    department: '',
    taskType: '',
    attachments: [],
    remarks: ''
  });
  
  // 计算属性
  const dialogVisible = computed({
    get: () => props.modelValue,
    set: (value) => emit('update:modelValue', value)
  });
  
  const isEdit = computed(() => !!props.task?.id);
  
  const departmentOptions = computed(() => {
    const departments = new Set<string>();
    props.personnelList.forEach(person => {
      departments.add(person.department);
    });
    return Array.from(departments).sort();
  });
  
  // 表单验证规则
  const rules: FormRules = {
    title: [
      { required: true, message: '请输入任务标题', trigger: 'blur' },
      { min: 2, max: 100, message: '标题长度在 2 到 100 个字符', trigger: 'blur' }
    ],
    description: [
      { required: true, message: '请输入任务描述', trigger: 'blur' },
      { min: 10, max: 500, message: '描述长度在 10 到 500 个字符', trigger: 'blur' }
    ],
    department: [
      { required: true, message: '请选择所属部门', trigger: 'change' }
    ],
    taskType: [
      { required: true, message: '请输入任务类型', trigger: 'blur' }
    ],
    priority: [
      { required: true, message: '请选择优先级', trigger: 'change' }
    ],
    status: [
      { required: true, message: '请选择任务状态', trigger: 'change' }
    ],
    deadline: [
      { required: true, message: '请选择截止时间', trigger: 'change' }
    ],
    assignedTo: [
      { required: true, message: '请选择分配人员', trigger: 'change' },
      { type: 'array', min: 1, message: '至少选择一个分配人员', trigger: 'change' }
    ]
  };
  
  // 禁用过去的日期
  const disabledDate = (time: Date) => {
    return time.getTime() < Date.now() - 8.64e7; // 禁用昨天之前的日期
  };
  
  // 监听任务变化
  watch(
    () => props.task,
    (newTask) => {
      if (newTask) {
        formData.value = { ...newTask };
        // 如果有附件，初始化文件列表
        if (newTask.attachments) {
          fileList.value = newTask.attachments.map((url, index) => ({
            name: `附件${index + 1}`,
            url
          }));
        }
      } else {
        // resetForm();
      }
    },
    { immediate: true, deep: true }
  );
  
  // 监听对话框显示状态
  watch(dialogVisible, (visible) => {
    if (visible && !props.task) {
      nextTick(() => {
        resetForm();
      });
    }
  });
  
  // 重置表单
  const resetForm = () => {
    formData.value = {
      title: '',
      description: '',
      assignedTo: [],
      assignedToNames: [],
      status: 'pending',
      priority: 'medium',
      deadline: '',
      department: '',
      taskType: '',
      attachments: [],
      remarks: ''
    };
    fileList.value = [];
    formRef.value?.clearValidate();
  };
  
  // 处理分配人员变化
  const handleAssignedToChange = (values: string[]) => {
    formData.value.assignedToNames = values;
  };
  
  // 文件上传相关
  const handlePreview = (file: UploadFile) => {
    if (file.url) {
      window.open(file.url, '_blank');
    }
  };
  
  const handleRemove = (file: UploadFile) => {
    const index = fileList.value.indexOf(file);
    if (index > -1) {
      fileList.value.splice(index, 1);
    }
  };
  
  const beforeUpload = (file: File) => {
    const isValidType = [
      'image/jpeg',
      'image/png',
      'application/pdf',
      'application/msword',
      'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
      'application/vnd.ms-excel',
      'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    ].includes(file.type);
    
    const isLt10M = file.size / 1024 / 1024 < 10;
    
    if (!isValidType) {
      ElMessage.error('只能上传 jpg/png/pdf/doc/docx/xls/xlsx 格式的文件！');
      return false;
    }
    
    if (!isLt10M) {
      ElMessage.error('文件大小不能超过 10MB！');
      return false;
    }
    
    return true;
  };
  
  // 保存任务
  const handleSave = async (publish: boolean) => {
    if (!formRef.value) return;
    
    try {
      await formRef.value.validate();
      
      saving.value = true;
      
      // 准备保存的任务数据
      const taskData: TaskInfo = {
        ...formData.value,
        attachments: fileList.value.map(file => file.url || file.response?.url || '').filter(Boolean)
      };
      
      // 如果是保存草稿，设置状态为 pending
      if (!publish) {
        taskData.status = 'pending';
      }
      
      // 模拟保存延迟
      await new Promise(resolve => setTimeout(resolve, 1000));
      
      emit('save', taskData);
      
      ElMessage.success(isEdit.value ? '任务更新成功！' : '任务发布成功！');
      
    } catch (error) {
      console.error('表单验证失败:', error);
    } finally {
      saving.value = false;
    }
  };
  
  // 关闭对话框
  const handleClose = () => {
    emit('cancel');
  };
  </script>
  
  <style lang="scss" scoped>
  .task-form {
    .priority-option {
      display: flex;
      align-items: center;
      gap: 8px;
      
      &.urgent {
        color: var(--el-color-danger);
      }
      
      &.high {
        color: var(--el-color-warning);
      }
      
      &.medium {
        color: var(--el-color-primary);
      }
      
      &.low {
        color: var(--el-color-info);
      }
    }
    
    .personnel-option {
      display: flex;
      justify-content: space-between;
      align-items: center;
      width: 100%;
      
      .name {
        font-weight: bold;
        color: var(--el-text-color-primary);
      }
      
      .department {
        font-size: 12px;
        color: var(--el-text-color-regular);
      }
      
      .nature {
        font-size: 12px;
        color: var(--el-color-primary);
        background: var(--el-color-primary-light-9);
        padding: 2px 6px;
        border-radius: 4px;
      }
    }
  }
  
  .dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 12px;
  }
  
  .upload-demo {
    :deep(.el-upload__tip) {
      margin-top: 8px;
      color: var(--el-text-color-regular);
      font-size: 12px;
    }
  }
  
  // 响应式设计
  @media (max-width: 768px) {
    .personnel-option {
      flex-direction: column;
      align-items: flex-start;
      gap: 4px;
    }
  }
  </style>